package cn.power.win.win_power.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import android.content.IntentFilter;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;

import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chad.library.adapter.base.callback.ItemDragAndSwipeCallback;
import com.chad.library.adapter.base.listener.OnItemDragListener;
import com.chad.library.adapter.base.listener.OnItemSwipeListener;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;

import org.greenrobot.eventbus.EventBus;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import cn.power.win.win_power.Device;
import cn.power.win.win_power.MyApp;
import cn.power.win.win_power.utils.ASUtils;
import cn.power.win.win_power.utils.AsShardPreUtils;
import cn.power.win.win_power.utils.DeviceBean;
import cn.power.win.win_power.utils.ItemDragAdapter2;
import cn.power.win.win_power.utils.ListDataSave;
import cn.power.win.win_power.utils.MessageEvent;
import cn.power.win.win_power.R;
import cn.power.win.win_power.acitivity.CustomScannerActivity;
import cn.power.win.win_power.acitivity.MainActivity;
import cn.power.win.win_power.utils.SpUtils;
import me.jessyan.autosize.internal.CustomAdapt;

/**
 * 节点
 */
public class NodeFragment extends Fragment implements CustomAdapt {

    private LinearLayout mLlscan;                   // 二维码扫一扫

    private RecyclerView mRecyclerView;             // 设备列表

    private ArrayList<Device> mData = new ArrayList<>(); // 列表数据源
    //private ArrayList<DeviceBean> mData2 = new ArrayList<>(); // 列表数据源
    private ItemDragAdapter2 mAdapter;               // 拖拽删除适配器

    private ItemDragAndSwipeCallback mItemDragAndSwipeCallback; //拖拽回调
    private ItemTouchHelper mItemTouchHelper;

    private ViewPager mViewPager;                      // 用于滑动切换的视图
    private String mCode;
    private View mView;
    private LocalBroadcastManager mBroadcastManager;
    //private ListDataSave mSave;
    Context mContext;
    private ListDataSave mSaveData;
    public static final String DIVICELIST ="SaveData";
  // private List<Device> mDivicelist;
    private List<Device> mDeviceList;
    private List<Device> mDevices;
    private PopupWindow mPopupWindow;
    //  private List<Device> mDeviceList;
    //private List<Device> mSave;
    // private RecyclerView mRvList2;
   // private ItemDragAdapter2 mAdapter2;
   // private ItemDragAndSwipeCallback mItemDragAndSwipeCallback2;
   // private ItemTouchHelper mItemTouchHelper2;
    /*  private MyReceiver mMyReceiver;*/

    // private TextView state_des;

    public NodeFragment() { }

    /*
     * 一定要在方法获取参数。在onCreateView中获取参数
     * ，而此方法在某些状态下并不会被调用，导致数据丢失。
     *
     * */
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 获取传递过来的数据
        Bundle arguments = getArguments();
        if (arguments != null) {
            mCode = arguments.getString("code");
            Log.e("mCode", mCode);

        }
        //注册广播
        registerReceiver();

        List<Object> listPreference = AsShardPreUtils.getInstant().getListPreference(DIVICELIST);
        mDeviceList = JSON.parseObject(listPreference.toString(), new TypeReference<List<Device>>() {
        });




    }

    private void registerReceiver() {

        mBroadcastManager = LocalBroadcastManager.getInstance(getActivity());
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("cn.power.win.win_power");
        mBroadcastManager.registerReceiver(mMyReceiver, intentFilter);

    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (mView == null) {
            mView = inflater.inflate(R.layout.fragment_node, container, false);
        }

        //初始化界面
        initView(mView);
        //保存数据
     //   mContext = getActivity();   //只能传这个上下文
     //   mSave = new ListDataSave(mContext, "Save");
        return mView;
    }

    private void initView(View view) {

        //   String code = getArguments().getString("code");
        //   String code = (String) getActivity().getIntent().getSerializableExtra("code");

        mLlscan = (LinearLayout) view.findViewById(R.id.ll_scan);
        //设置扫一扫点击事件
        mLlscan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //zing定义 跳转扫一扫界面
                IntentIntegrator.forSupportFragment(NodeFragment.this)
                        .setCaptureActivity(CustomScannerActivity.class)
                        .initiateScan();

            }
        });
        mRecyclerView = (RecyclerView) view.findViewById(R.id.rv_list);

        //设置布局管理器
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        OnItemDragListener listener = new OnItemDragListener() {
            @Override
            public void onItemDragStart(RecyclerView.ViewHolder viewHolder, int pos) {
              //  Log.d(TAG, "drag start");
                BaseViewHolder holder = ((BaseViewHolder) viewHolder);
                // holder.setTextColor(R.id.tv, Color.WHITE);
            }

            @Override
            public void onItemDragMoving(RecyclerView.ViewHolder source, int from, RecyclerView.ViewHolder target, int to) {
               // Log.d(TAG, "move from: " + source.getAdapterPosition() + " to: " + target.getAdapterPosition());
            }

            @Override
            public void onItemDragEnd(RecyclerView.ViewHolder viewHolder, int pos) {
               // Log.d(TAG, "drag end");
                BaseViewHolder holder = ((BaseViewHolder) viewHolder);
                // holder.setTextColor(R.id.tv, Color.BLACK);
            }
        };
        OnItemSwipeListener onItemSwipeListener = new OnItemSwipeListener() {
            @Override
            public void onItemSwipeStart(RecyclerView.ViewHolder viewHolder, int pos) {
               // Log.d(TAG, "view swiped start: " + pos);
                BaseViewHolder holder = ((BaseViewHolder) viewHolder);
                // holder.setTextColor(R.id.tv, Color.WHITE);
            }

            @Override
            public void clearView(RecyclerView.ViewHolder viewHolder, int pos) {
               // Log.d(TAG, "View reset: " + pos);
                BaseViewHolder holder = ((BaseViewHolder) viewHolder);
                // holder.setTextColor(R.id.tv, Color.BLACK);
            }

            @Override
            public void onItemSwiped(RecyclerView.ViewHolder viewHolder, int pos) {
               // Log.d(TAG, "View Swiped: " + pos);
            }

            @Override
            public void onItemSwipeMoving(Canvas canvas, RecyclerView.ViewHolder viewHolder, float dX, float dY, boolean isCurrentlyActive) {
                //  canvas.drawColor(ContextCompat.getColor(getActivity(), R.color.themeColor));

            }
        };
        // mData.add("GYF00001");
        //假数据
 /*     Device device3 = new Device();
        device3.setId("GPRSG0000478");
        //  device.setState("未连接");
        mData.add(device3);*/

      // 当没有数据时，再检查有没有保存的数据


        mAdapter = new ItemDragAdapter2(mData);

        if (mDeviceList.size()>0) {
            mAdapter.addData(mDeviceList);
            mAdapter.notifyDataSetChanged();

        }

        mItemDragAndSwipeCallback = new ItemDragAndSwipeCallback(mAdapter);

        mItemTouchHelper = new ItemTouchHelper(mItemDragAndSwipeCallback);

        mItemTouchHelper.attachToRecyclerView(mRecyclerView);

        mItemDragAndSwipeCallback.setSwipeMoveFlags(ItemTouchHelper.START | ItemTouchHelper.END);

        mAdapter.enableSwipeItem();

        mAdapter.setOnItemSwipeListener(onItemSwipeListener);

        mAdapter.enableDragItem(mItemTouchHelper);

        mAdapter.setOnItemDragListener(listener);

        mRecyclerView.setAdapter(mAdapter);

        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {

            @Override
            public void onItemClick(BaseQuickAdapter adapter, final View view, int position) {
            //  获取条目子 控件的id
                String ID = mAdapter.getData().get(position).getId();

                EventBus.getDefault().post(new MessageEvent(ID));
                // 跳转到Fragment 与MAinActivity中的方法对接
                final MainActivity mainActivity = (MainActivity) getActivity();
                mainActivity.setFragment2Fragment(new MainActivity.Fragment2Fragment() {
                    @Override
                    public void gotoFragment(ViewPager viewPager) {
                        viewPager.setCurrentItem(1);
                    }
                });
                //携带参数方法（1）
                // mainActivity.setName(mID);
                //携带参数方法（2）
                mainActivity.forSkip();
                //判断获取的ID是不是以GPRS开头的




            }
        });

        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.item_tv_del:
                        Toast.makeText(getActivity(), "删除", Toast.LENGTH_SHORT).show();
                        mAdapter.remove(position);
                        break;
                    case R.id.item_tv_edit:

                        // 1.判断密码是否为空
                        DeviceBean mDeviceBean = SpUtils.getObject(MyApp.context, mAdapter.getData().get(position).getId());
                        if (mDeviceBean == null) {
                            Toast.makeText(getActivity(), "蓝牙不需要密码", Toast.LENGTH_SHORT).show();
                        }else {
                            int size = mDeviceBean.getPassword().size()-1;

                            String mOldPwd = mDeviceBean.getPassword().get(size);
                            String beanMac = mDeviceBean.getMac();

                            if (beanMac.startsWith("GPRS")) {
                                ShowModifyPassword(beanMac,mOldPwd);
                            }else if (beanMac.startsWith("RJ45")){
                                ShowModifyPassword(beanMac,mOldPwd);
                            }/*else {
                                Toast.makeText(getActivity(), "蓝牙不需要密码", Toast.LENGTH_SHORT).show();
                            }*/

                        }




                        break;
                    case R.id.tv_name:
                     //   Toast.makeText(getActivity(), "跳转", Toast.LENGTH_SHORT).show();
                        //  获取条目子 控件的id
                        String ID = mAdapter.getData().get(position).getId();

                        EventBus.getDefault().post(new MessageEvent(ID));
                        // 跳转到Fragment 与MAinActivity中的方法对接
                        final MainActivity mainActivity = (MainActivity) getActivity();
                        mainActivity.setFragment2Fragment(new MainActivity.Fragment2Fragment() {
                            @Override
                            public void gotoFragment(ViewPager viewPager) {
                                viewPager.setCurrentItem(1);
                            }
                        });
                        //携带参数方法（1）
                        // mainActivity.setName(mID);
                        //携带参数方法（2）
                        mainActivity.forSkip();
                        //判断获取的ID是不是以GPRS开头的



                        break;
                }
            }
        });

    }
    // 更改输入密码
    private void ShowModifyPassword(String beanMac, String mOldPwd) {
        View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.popupwindow_modify_password, null);
        mPopupWindow = new PopupWindow(contentView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);
        mPopupWindow.setContentView(contentView);
        mPopupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

        mPopupWindow.setOutsideTouchable(true);// 设置允许在外点击消失
        mPopupWindow.setFocusable(true);
        //初始化界面
        final EditText etPassword = (EditText) contentView.findViewById(R.id.et_password);
        TextView tvTrueButton = (TextView) contentView.findViewById(R.id.tv_true_button);
        TextView tvCancelButton = (TextView) contentView.findViewById(R.id.tv_cancel_button);
        TextView tvPassword = (TextView) contentView.findViewById(R.id.tv_password);
        tvPassword.setText(mOldPwd);

        LinearLayout ll = (LinearLayout) contentView.findViewById(R.id.ll);



        ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
             //   mPopupWindow.dismiss();
            }
        });
        // 取消
        tvCancelButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPopupWindow.dismiss();
                //    finish();
            }
        });
        // 确认
        tvTrueButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ASUtils.isCanUse(etPassword.getText().toString().trim())) {

                    List<String> mPassword = new ArrayList<>();
                    mPassword.add(etPassword.getText().toString().trim());
                    DeviceBean mDeviceBean = new DeviceBean(beanMac,mPassword);
                    // 以mac地址为键值来存取对象
                    SpUtils.putObject(MyApp.context,mDeviceBean.getMac(),mDeviceBean);
                    //取消弹窗
                    mPopupWindow.dismiss();
                    // finish();

                } else {
                    Toast.makeText(getActivity(), "请先输入密码", Toast.LENGTH_SHORT).show();
                }

            }


        });

        ColorDrawable dw = new ColorDrawable(0x70000000);
        mPopupWindow.setBackgroundDrawable(dw);
        mPopupWindow.showAtLocation(contentView, Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0);

    }

    /*
     * 扫描二维码获取请求码中的解析数据
     * */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (requestCode) {
            case 49374:
                IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
             //   Log.i("requestCode", requestCode + "");
                if (result != null) {
                    if (result.getContents() == null) {
                    //   Toast.makeText(getActivity(), "取消扫描", Toast.LENGTH_LONG).show();
                    } else {
                        // 保存扫描的结果：
                        //通过一个集合保存新增节点：
                        String content = result.getContents();
                        if (content.startsWith("GPRS")) {
                            ShowInputPassword(content);
                        }else if (content.startsWith("RJ45")){
                            ShowInputPassword(content);
                        }

                        Device device = new Device();
                        //获取扫描设备的id
                        device.setId(result.getContents());
                        mData.add(device);

                        mAdapter.notifyDataSetChanged();
                        AsShardPreUtils.getInstant().setListPreference(DIVICELIST,  mAdapter.getData());

                       //Toast.makeText(getActivity(), "Scanned: " + result.getContents(), Toast.LENGTH_LONG).show();
                    }
                }
                break;

        }

    }
    // 输入密码
    private void ShowInputPassword(String content) {
        View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.popupwindow_password, null);
        final PopupWindow popupWindow = new PopupWindow(contentView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);
        popupWindow.setContentView(contentView);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);// 设置允许在外点击消失
        //初始化界面
        final EditText etPassword = (EditText) contentView.findViewById(R.id.et_password);
        TextView tvTrue = (TextView) contentView.findViewById(R.id.tv_true);
        TextView tvCancel = (TextView) contentView.findViewById(R.id.tv_cancel);
        LinearLayout ll = (LinearLayout) contentView.findViewById(R.id.ll);

        ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        // 取消
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            //    finish();
            }
        });
        // 确认
        tvTrue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!ASUtils.isCanUse(etPassword.getText().toString().trim())) {
                    Toast.makeText(getActivity(),"请先输入密码",Toast.LENGTH_SHORT).show();
                }else {
                    List<String> mPassword = new ArrayList<>();
                    mPassword.add(etPassword.getText().toString().trim());
                    DeviceBean mDeviceBean = new DeviceBean(content,mPassword);
                    // 以mac地址为键值来存取对象
                    SpUtils.putObject(MyApp.context,mDeviceBean.getMac(),mDeviceBean);
                    //取消弹窗
                    popupWindow.dismiss();
                   // finish();

                }

            }


        });

        ColorDrawable dw = new ColorDrawable(0x70000000);
        popupWindow.setBackgroundDrawable(dw);
        popupWindow.showAtLocation(contentView, Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0);

    }

    //通过手动输入后，在此接受广播添加到集合。

    private BroadcastReceiver mMyReceiver = new BroadcastReceiver() {
        private String mRecode;
        //  private String mRecode;
      /*  private String mRecode2;*/

        @Override
        public void onReceive(Context context, Intent intent) {

            final String code = intent.getStringExtra("data");
                // 这地方只能在主线程中刷新UI,子线程中无效，因此用Handler来实现

                new Handler().post(new Runnable() {
                    public void run() {
                        //在这里来写你需要刷新的地方
                        Device device = new Device();
                        device.setId(code);
                        mData.add(device);
                        //保存添加后的集合

                        //刷新界面
                        mAdapter.notifyDataSetChanged();
                   //   mSave.setDataList("Bean",mData);
                      AsShardPreUtils.getInstant().setListPreference(DIVICELIST, mAdapter.getData());

                    }
                });


        }
    };

    @Override
    public void onPause() {
        super.onPause();

        Log.e("TAG","onPause");
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.e("TAG","onStop");
    }

    /**
     * 注销广播
     */
    @Override
    public void onDetach() {
        super.onDetach();
        mBroadcastManager.unregisterReceiver(mMyReceiver);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        //退出app的时候，保存客户最终想要保存的数据
        Log.e("OnDestroy","onDestroy");
        AsShardPreUtils.getInstant().setListPreference(DIVICELIST,  mAdapter.getData());
    }


    @Override
    public boolean isBaseOnWidth() {
        return true;
    }

    @Override
    public float getSizeInDp() {
        return 670;
    }
}
